// src/router/index.ts
import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router' // 单独用 import type 导入类型

import Login from '../components/Login.vue'
import Register from '../components/Register.vue'
import Dashboard from '../components/Dashboard.vue'
import AddSchedule from '../components/AddSchedule.vue'
import ViewSchedule from '../components/ViewSchedule.vue'
import Profile from '../components/Profile.vue'
import AdminUsers from '../components/AdminUsers.vue'
import AdminUserView from '../components/AdminUserView.vue'
import AdminUserEdit from '../components/AdminUserEdit.vue'
import AdminUserDelete from '../components/AdminUserDelete.vue'
// DeleteSchedule and EditSchedule may not exist; load lazily if present to avoid build errors
const DeleteSchedule = () => import('../components/DeleteSchedule.vue')
const EditSchedule = () => import('../components/EditSchedule.vue')

// 定义路由规则
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/login' // 根路径默认跳转到 login
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: Dashboard
  },
  {
    path: '/schedule/add',
    name: 'AddSchedule',
    component: AddSchedule
  },
  {
    path: '/schedule/view',
    name: 'ViewSchedule',
    component: ViewSchedule
  },
  {
    path: '/profile',
    name: 'Profile',
    component: Profile
  },
  {
    path: '/admin/users',
    name: 'AdminUsers',
    component: AdminUsers
  },
  {
    path: '/admin/users/view/:username',
    name: 'AdminUserView',
    component: AdminUserView
  },
  {
    path: '/admin/users/edit/:username',
    name: 'AdminUserEdit',
    component: AdminUserEdit
  },
  {
    path: '/admin/users/delete/:username',
    name: 'AdminUserDelete',
    component: AdminUserDelete
  },
  {
    path: '/schedule/delete',
    name: 'DeleteSchedule',
    component: DeleteSchedule
  },
  {
    path: '/schedule/edit',
    name: 'EditSchedule',
    component: EditSchedule
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/login' // 未匹配路径跳转到登录页
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL), // 使用 HTML5 History 模式（无 # 号）
  routes // 注册路由规则
})
// 全局前置守卫：保护 /admin 路由，仅允许 role === 'admin' 访问（基于 localStorage 的简单前端保护）
router.beforeEach((to, _from, next) => {
  if (to.path.startsWith('/admin')) {
    try {
      const role = localStorage.getItem('role') || ''
      if (role === 'admin') {
        next()
        return
      }
    } catch (e) {
      // ignore
    }
    next('/login')
    return
  }
  next()
})

export default router